//
//  ByUIOrderDetailVC.m
//  oc_knowledge
//
//  Created by mc on 17/1/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIOrderDetailVC.h"
//Api
#import "ByApiOderDetail.h"
#import "ByApiOrder.h"

//Cell
#import "ByCellOrderDetailFirst.h"
#import "ByCellOrderDetailSecond.h"
#import "ByCellOrderDetailThird.h"
#import "ByCellOrder.h"

//Other
#import "ZKBombView.h"

//VC
#import "ByUIOrderDetailRefundVC.h"
#import "ByUIOrderEvaluateVC.h"
#import "ByUIOrderDetailRefundVC.h"
#import "ByUIOrderPayVC.h"

#define ButtonColor [UIColor colorWithR:253 g:125 b:69]
@interface ByUIOrderDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ByModelOrderDetail *detailModel;
@property (nonatomic, strong) ByLayoutOrderDetailFirst *firstLayout;

@property (nonatomic, strong) UIView *bottomView;                         //底部按钮视图
@property (nonatomic, strong) ZKBombView *reasonView;                     //取消订单视图
@end

@implementation ByUIOrderDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addLeftBackBarButtonItem];
    self.title = @"订单详情";
    [self initTableView];
    [self createBottomView];
    
    [self initData];
//    [self initDataTest];
}
#pragma mark ---getter
-(ByLayoutOrderDetailFirst *)firstLayout{
    if (!_firstLayout) {
        _firstLayout = [[ByLayoutOrderDetailFirst alloc] init];
    }
    return _firstLayout;
}
-(ByModelOrderDetail *)detailModel{
    if (!_detailModel) {
        _detailModel = [[ByModelOrderDetail alloc] init];
    }
    return _detailModel;
}

-(ZKBombView *)reasonView{
    if (_reasonView == nil) {
        _reasonView = [[ZKBombView alloc] init];
        _reasonView.positionMode = ZKBombPositionModeBottom;
        _reasonView.contentMode = ZKBombContentModePicker;
        _reasonView.popMode = ZKBombPopModeBottom;
        _reasonView.dataItems = @[@"我不想买了",@"信息填写错误，重新拍",@"卖家缺货",@"同城见面交易",@"其他原因"];
    }
    return _reasonView;
}

#pragma mark ---获取数据
- (void)initData{
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.uid = BY_USER.uid;
    model.s_id = BY_USER.s_id;
    model.order_code = self.order_code;
    [self performSelector:@selector(showLoading) withObject:nil afterDelay:0.2];
    [ByApiOderDetail getOrderDetail:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        self.detailModel = result.data;
        self.firstLayout.model = self.detailModel;
        [self.tableView reloadData];
        self.tableView.hidden = NO;
        if (self.order_status == 2) {
            self.bottomView.hidden = YES;
        }else{
            self.bottomView.hidden = NO;
        }
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

/**用于延缓调用*/
- (void)showLoading{
    [ByCoreToolAlert showLoadind:@"加载中..." hasMasker:YES];
}
//我的测试数据
- (void)initDataTest{
    if (self.order_status == 3) {
        self.detailModel.logisticInfo = @"快件正在揽件，请耐心等待，顺丰快件祝您新春快乐";
        self.detailModel.logistic_time = @"2017-2-8 16:26";
    }
    self.detailModel.order_code = @"T26788935675779";
    self.detailModel.createtime = @"2017-2-7 6:26";
    self.detailModel.pay_code = @"2017020887763665537778";
    self.detailModel.query_status = [NSString stringWithFormat:@"%ld",self.order_status];
    NSDictionary *dic  = [NSDictionary dictionaryWithObject:@"24.90" forKey:@"商品总价"];
    NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"0.00" forKey:@"运费(快递)"];
    NSDictionary *dic2 = [NSDictionary dictionaryWithObject:@"24.90" forKey:@"订单总价"];
    self.detailModel.payInfoAry = @[dic,dic1,dic2];
    //商品数组
    ByModelOrderListItemProduct *proModel = [[ByModelOrderListItemProduct alloc] init];
    proModel.name = @"韩国压发饰洗脸发带韩版布艺简约交叉甜美发箍宽边百搭";
    proModel.price = @"280";
    proModel.ori_price = @"180";
    proModel.sku_desc = @"颜色分类:模特款平板款－驼色";
    proModel.count = @(20);
    proModel.tag = @"七天退换";
    self.detailModel.items = @[proModel];
    self.firstLayout.model = self.detailModel;
    [self.tableView reloadData];
    self.tableView.hidden = NO;
}

#pragma mark ---创建视图
//初始化表视图
-(void)initTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 50) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = TABLE_COLOR;
    self.view.backgroundColor = TABLE_COLOR;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.hidden = YES;
}

//创建底部按钮视图
- (void)createBottomView{
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, 50)];
    _bottomView.backgroundColor = [UIColor whiteColor];
    _bottomView.hidden = YES;
    [self.view insertSubview:_bottomView aboveSubview:_tableView];
    NSArray *buttonAry;
    switch (self.order_status){
        case 1:  //待付款
        {
            buttonAry = @[@"付款",@"取消订单",@"联系卖家"];
        }
            break;
        case 2:  //代发货
            break;
        case 3:  //待收货
        {
            buttonAry = @[@"确认收货",@"查看物流"];
        }
            break;
        case 4: //已收货
        {
            buttonAry = @[@"评价",@"删除订单"];
        }
            break;
        case 7: //已完成
        {
            buttonAry = @[@"删除订单"];
        }
            break;
        case 8://已关闭
        {
            buttonAry = @[@"删除订单"];
        }
            break;
            
    }
    CGFloat x,y,width,height;
    y = 10;
    width = [@"删除订单" getSizeOfString:14].width + 20;
    height = 30;
    for (int i = 0; i < buttonAry.count; i ++) {
        CGFloat margin = 15;
        x = SCREEN_WIDTH - (width + margin) * (i+1) ;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [button setTitle:buttonAry[i] forState:UIControlStateNormal];
        [_bottomView addSubview:button];
        button.layer.borderWidth = 1;
        button.layer.cornerRadius = 4.0;
        button.titleLabel.font = FONT(14);
        if (i == 0) {
            [button setTitleColor:ButtonColor forState:UIControlStateNormal];
            button.layer.borderColor = ButtonColor.CGColor;
        }else{
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.layer.borderColor = [UIColor colorWithWhite:0.95 alpha:1].CGColor;
        }
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }

}

#pragma mark ---UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section != 1) {
        return 1;
    }
    else{
//        if (self.detailModel.query_status.integerValue != 1) {
//            return self.detailModel.items.count + 2; //待定
//        }
//        else
            return self.detailModel.items.count + 1;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section != 1) {
        return 0.0001;
    }
    else
        return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ByCellOrderDetailFirst *cell = [ByCellOrderDetailFirst cellWithTableView:tableView];
        cell.layout = self.firstLayout;
        return cell;
    }
    else if (indexPath.section == 1){
        NSInteger itemCount = self.detailModel.items.count;          //商品数量
        if (indexPath.row < itemCount) {
            ByCellOrder *cell = [ByCellOrder cellWithTableView:tableView];
            ByModelOrderListItemProduct *proModel = self.detailModel.items[indexPath.row];
            proModel.isFromDetail = YES;
            proModel.order_status = [NSString stringWithFormat:@"%li",self.order_status];
            cell.model = proModel;
            cell.refundBlock = ^(ByModelOrderListItemProduct *model){
                NSLog(@"%@",model);
                ByUIOrderDetailRefundVC *vc = [[ByUIOrderDetailRefundVC alloc] init];
                vc.refundPrice = self.detailModel.price;
                [self by_normalPush:vc hasNavi:YES];
                
            };
            return cell;
        }
//        else if (indexPath.row == itemCount && self.detailModel.query_status.integerValue != 1){
//            /**通用cell*/
//            static NSString *indentier = @"orderDetailActionCell";
//            UITableViewCell *customCell = [tableView dequeueReusableCellWithIdentifier:indentier];
//            if (customCell == nil) {
//                customCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
//                customCell.selectionStyle = UITableViewCellSelectionStyleNone;
//                customCell.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
//            }
//            for (UIView *subviews in customCell.subviews) {
//                [subviews removeFromSuperview];
//            }
//            NSArray *buttonAry;
//            switch (self.detailModel.query_status.integerValue){
//                case 1:  //待付款
//                    break;
//                case 2:  //待发货
//                    buttonAry = @[@"退款"];
//                    break;
//                case 3:  //待收货
//                {
//                    buttonAry = @[@"退款"];
//                }
//                    break;
//                case 4:  //已收货
//                    break;
//                case 7:  //已完成
//                    break;
//                case 8:  //已关闭
//                    break;
//                    
//            }
//            CGFloat x,y,width,height;
//            y = 10;
//            width = [@"删除订单" getSizeOfString:14].width + 20;
//            height = 30;
//            for (int i = 0; i < buttonAry.count; i ++) {
//                CGFloat margin = 15;
//                x = SCREEN_WIDTH - (width + margin) * (i+1) ;
//                UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
//                [button setTitle:buttonAry[i] forState:UIControlStateNormal];
//                [customCell addSubview:button];
//                button.layer.borderWidth = 1;
//                button.layer.cornerRadius = 4.0;
//                button.titleLabel.font = FONT(14);
//                button.backgroundColor = [UIColor whiteColor];
//                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//                button.layer.borderColor = [UIColor colorWithWhite:0.90 alpha:1].CGColor;
//                [button addTarget:self action:@selector(cellBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//            }
//            return customCell;
//
//        }
        else{
            ByCellOrderDetailSecond *cell = [ByCellOrderDetailSecond cellWithTableView:tableView];
            cell.model = self.detailModel;
            return cell;
        }
    }
    else{
        ByCellOrderDetailThird *cell = [ByCellOrderDetailThird cellWithTableView:tableView];
        cell.detailModel = self.detailModel;
        return cell;
    
    }
        
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        headerView.backgroundColor = [UIColor whiteColor];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
        [img setImageWithURL:[NSURL URLWithString:self.detailModel.store_logo] placeholderImage:DEFAULT_IMAGE completed:nil];
        [headerView addSubview:img];
        
        UILabel *sotreNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(img.right + 10, 10, SCREEN_WIDTH - 40, 20)];
        sotreNameLabel.font = FONT(16);
        sotreNameLabel.textColor = [UIColor blackColor];
        sotreNameLabel.text = self.detailModel.store_name;
        return headerView;
    }
    else
        return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.firstLayout.cellFrame.size.height;
    }
    else if(indexPath.section == 1){
        NSInteger itemCount = self.detailModel.items.count;          //商品数量
        if (indexPath.row < itemCount) {
            if (self.order_status != 1 && self.order_status != 8) {
                return 92 + 50;
            }else
                return 92 ;
        }
//        else if (indexPath.row == itemCount && self.detailModel.query_status.integerValue != 1){
//            return 50;
//        }
        else
            return self.detailModel.payInfoAry.count *(15 + 10) + 40;
    }
    else
        return 100;
}
#pragma mark --按钮点击事件
- (void)buttonAction:(UIButton *)button{
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.uid = BY_USER.uid;
    model.order_code = self.detailModel.order_code;
    model.s_id = BY_USER.s_id;
    if ([button.titleLabel.text isEqualToString:@"联系卖家"]) {
        [ByCoreToolAlert showOnlyText:@"联系卖家"];
        ByUIOrderDetailRefundVC *vc = [[ByUIOrderDetailRefundVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
    }
    else if ([button.titleLabel.text isEqualToString:@"取消订单"]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否取消订单" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [ByCoreToolAlert showLoadind:@"处理中..."];
            [ByApiOrder cancleOrder:model success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.data];
                [self dismissViewControllerAnimated:YES completion:^{
                    if (self.successBlock) {
                        self.successBlock();
                    }
                }];
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.msg];
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:sureAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    else if ([button.titleLabel.text isEqualToString:@"付款"]){
        [ByCoreToolAlert showLoadind:@"正在验证订单..."];
        [ByApiOrder repayOrder:model success:^(ByNetBaseResult *result) {
            [ByCoreToolAlert hideHud];
            
            ByModelOrderPay *paymodel = result.data;
            ByUIOrderPayVC *vc = [[ByUIOrderPayVC alloc] init];
            vc.type = 1;
            vc.payModel = paymodel;
            vc.fee = paymodel.total_price;
            [self by_normalPush:vc hasNavi:YES];
            
            
        } failure:^(ByNetBaseResult *result) {
            [ByCoreToolAlert showOnlyText:result.msg];
        }];

    }
    else if ([button.titleLabel.text isEqualToString:@"确认收货"]){
//        [ByCoreToolAlert showOnlyText:@"确认收货"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否确认收货" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
            params.uid = BY_USER.uid;
            params.s_id = BY_USER.s_id;
            params.order_code = self.detailModel.order_code;
            [ByCoreToolAlert showLoadind:@"正在确认收货..."];
            [ByApiOrder confirmOrder:params success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.data];
                [self dismissViewControllerAnimated:YES completion:^{
                    if (self.successBlock) {
                        self.successBlock();
                    }
                }];
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showFailureWithText:result.msg];
            }];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:sureAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];


    }
    else if ([button.titleLabel.text isEqualToString:@"查看物流"]){
        [ByCoreToolAlert showOnlyText:@"查看物流"];
        
    }
    else if ([button.titleLabel.text isEqualToString:@"延长收货"]){
        [ByCoreToolAlert showOnlyText:@"延长收货"];
        
    }
    else if ([button.titleLabel.text isEqualToString:@"评价"]){
        [ByCoreToolAlert showOnlyText:@"评价"];
        ByUIOrderEvaluateVC *vc = [[ByUIOrderEvaluateVC alloc] init];
        vc.model = self.detailModel;
        [self by_normalPush:vc hasNavi:YES];
    }
    else if ([button.titleLabel.text isEqualToString:@"删除订单"]){
        [ByCoreToolAlert showOnlyText:@"删除订单"];
        
    }
    
}

//单元格按钮点击事件
- (void)cellBtnAction:(UIButton *)btn{
    ByUIOrderDetailRefundVC *vc = [[ByUIOrderDetailRefundVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
}

@end
